#!/bin/sh

. ./realpath.sh

setUp() {
    unset _system_readlink _gnu_stat_readlink _bsd_stat_readlink

    _has_command() {
        return 1
    }
}

it_calls_system_readlink_when_has_command_readlink_is_true() {
    _has_command() {
        test "$1" = readlink
    }

    local readlink_arg1 readlink_arg2
    _system_readlink() {
        readlink_arg1="$1"
        readlink_arg2="$2"
    }

    readlink -- some/path

    assertEquals -- "$readlink_arg1"
    assertEquals some/path "$readlink_arg2"
}

it_calls__gnu_stat_readlink_when_has_command_readlink_is_false() {
    local called
    _gnu_stat_readlink() {
        called=1
    }

    readlink -- some/path

    assertNotNull "_gnu_stat_readlink called" "$called"
}

it_passes_actual_arg_to__gnu_stat_readlink() {
    local arg
    _gnu_stat_readlink() {
        arg="$1"
    }

    readlink -- some/path

    assertEquals some/path "$arg"
}

it_passes_first_arg_to__gnu_stat_readlink_when_no_dashes() {
    local arg
    _gnu_stat_readlink() {
        arg="$1"
    }

    readlink some/path

    assertEquals some/path "$arg"
}

it_doesnt_call__bsd_stat_readlink_when__gnu_stat_readlink_returns_true() {
    _gnu_stat_readlink() {
        return 0
    }

    local called
    _bsd_stat_readlink() {
        called=1
    }

    readlink -- some/path

    assertNull "_bsd_stat_readlink not called" "$called"
}

it_calls__bsd_stat_readlink_when__gnu_stat_readlink_returns_false() {
    _gnu_stat_readlink() {
        return 1
    }

    local called
    _bsd_stat_readlink() {
        called=1
    }

    readlink -- some/path

    assertNotNull "_bsd_stat_readlink called" "$called"
}

it_passes_actual_arg_to__bsd_stat_readlink() {
    _gnu_stat_readlink() {
        return 1
    }

    local arg
    _bsd_stat_readlink() {
        arg="$1"
    }

    readlink -- some/path

    assertEquals some/path "$arg"
}

##### Test Harness #####

# suite() -- find and register tests to be run
#   Derived from Gary Bernhardt's screencast #68
#   (https://www.destroyallsoftware.com/screencasts/catalog/test-driving-shell-scripts)
suite() {
    local name tests
    tests=$(grep ^it_ "$0" | cut -d '(' -f 1)
    for name in $tests; do
        suite_addTest "$name"
    done
}

if hash shunit2 2>/dev/null; then
    . shunit2
else
    echo 'Error: shunit2(1) could not be located. Please install it on your $PATH.' >&2
    exit 1
fi
